#include "icysettings.h"

IcySettings::IcySettings()
{
    QCoreApplication::setOrganizationName("AxSoftware");
    QCoreApplication::setOrganizationDomain("icyqt.org");
    QCoreApplication::setApplicationName("IcyQt IM Client");
    QCoreApplication::setApplicationVersion("0.0.1");
    settings = new QSettings;
    //settings->setSystemIniPath(QDir::currentPath());
}

IcySettings::~IcySettings()
{
    delete settings;
}

_fastcall QIcon IcySettings::getIcon(const QString &sIcon)
{
    QUrl url(sIcon);
    QString dir;
    if ( url.scheme() == "status" )
        dir = "resources/icons/icq/default/";
    else
    if ( url.scheme() == "xstatus" )
        dir = "resources/icons/xstatus/default/";
    QPixmap pixmap(dir + url.host() + ".png");
    QIcon icon(pixmap);
    return icon;
}

_fastcall void IcySettings::getAccounts(accList *accounts)
{
    bool ok;
    QFile file("accounts.ini");
    if ( !file.open(QFile::ReadOnly) )
        return;

    QString sCount(file.readLine());
    if ( sCount.indexOf("\n") > 0 )
        sCount.chop(2);
//    qDebug() << sCount;

    int iCount = sCount.toInt(&ok);
//    accounts = new IcyAccount[*iCount];

    QString sStr;

    for ( int i = 0; i < iCount; i++ ){
        sStr = file.readLine();
        if ( sStr.indexOf("\n") > 0 )
            sStr.chop(2);
//        qDebug() << sStr;
        IcyAccount account;
        account.sScreenName = sStr.mid(0, sStr.indexOf(";"));
        sStr.remove(0, sStr.indexOf(";") + 1);
        account.sPassword = sStr.mid(0, sStr.indexOf(";"));
        sStr.remove(0, sStr.indexOf(";") + 1);
        account.bSavePassword = sStr.indexOf("1") > 0;
        accounts->append(account);
//        qDebug() << accounts->at(i).sScreenName << ";" << accounts->at(i).sPassword;
    }
    file.close();
//    qDebug() << "Done";
}

void IcySettings::saveAccount(const QString &sScreenName,
                              const QString &sPassword,
                              const bool bSavePassword,
                              const int iIndex)
{
    if ( sScreenName.isEmpty() || (bSavePassword && sPassword.isEmpty()) )
        return;

    bool ok;
    QSettings accSettings("accounts.ini", "", 0);
    accSettings.beginGroup("accounts");

    int iCount = iIndex;
    if ( iCount == -1 ){
        iCount = accSettings.value("count", 0).toInt(&ok);
        if ( !ok )
            return;
        accSettings.setValue("count", ++iCount);
    }

    QString sVal;
    sVal.setNum(iCount);
    accSettings.setValue("account" + sVal + "/ScreenName", sScreenName);
    accSettings.setValue("account" + sVal + "/Password", sPassword);
    accSettings.setValue("account" + sVal + "/SavePassword", bSavePassword);
    accSettings.endGroup();
}

void IcySettings::loadSettings()
{
    //
}

void IcySettings::saveSettings()
{
    //
}
